<template>
  <div class="modify-email-page">
    <ResponsiveNav />

    <div class="page-content">
      <!-- 面包屑导航 -->
      <div class="page-nav">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/account/profile' }">
              <i class="fas fa-chevron-left"></i> {{ $t('返回个人资料') }}
            </el-breadcrumb-item>
            <el-breadcrumb-item>{{ $t('修改邮箱') }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>

      <!-- 主要内容 -->
      <div class="main-card">
        <h1 class="page-title">{{ $t('修改邮箱') }}</h1>

        <!-- 步骤条 -->
        <el-steps :active="currentStep" finish-status="success" simple class="steps">
          <el-step>
            <template #title>
              <span class="step-title">{{ $t('验证原邮箱') }}</span>
            </template>
          </el-step>
          <el-step>
            <template #title>
              <span class="step-title">{{ $t('设置新邮箱') }}</span>
            </template>
          </el-step>
          <el-step>
            <template #title>
              <span class="step-title">{{ $t('完成') }}</span>
            </template>
          </el-step>
        </el-steps>

        <div class="step-container">
          <transition name="fade" mode="out-in">
            <div :key="currentStep" class="step-content">
              <template v-if="currentStep === 0">
                <div class="verify-step">
                  <p class="step-desc">{{ $t('我们将向您的邮箱') }} {{ maskEmail(currentEmail) }} {{ $t('发送验证码') }}</p>
                  <verification-code-input v-model:code="verificationCode" :has-error="verifyError"
                    @complete="handleVerifyComplete" />
                  <div class="resend-wrapper">
                    <el-button link :disabled="countdown > 0" @click="handleResend">
                      {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
                    </el-button>
                  </div>
                </div>
              </template>

              <template v-else-if="currentStep === 1">
                <div class="set-new-step">
                  <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
                    <el-form-item :label="$t('新邮箱地址')" prop="newEmail">
                      <el-input v-model="form.newEmail" :placeholder="$t('请输入新的邮箱地址')">
                        <template #prefix>
                          <i class="fas fa-envelope"></i>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item :label="$t('验证码')" prop="verifyCode">
                      <verification-code-input v-model:code="form.verifyCode" :has-error="newEmailVerifyError"
                        @complete="handleNewEmailVerifyComplete" />
                      <div class="resend-wrapper">
                        <el-button link :disabled="newEmailCountdown > 0" @click="handleNewEmailResend">
                          {{ newEmailCountdown > 0 ? `${$t('重新发送')} (${newEmailCountdown}s)` : $t('发送验证码') }}
                        </el-button>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </template>

              <template v-else>
                <div class="complete">
                  <div class="success-icon">
                    <i class="fas fa-check-circle"></i>
                  </div>
                  <h3>{{ $t('邮箱修改成功') }}</h3>
                  <p>{{ $t('您的邮箱已成功修改为') }} {{ form.newEmail }}</p>
                </div>
              </template>
            </div>
          </transition>
        </div>

        <!-- 底部按钮 -->
        <div class="bottom-actions">
          <el-button v-if="currentStep < 2" @click="handleCancel">{{ $t('取消') }}</el-button>
          <el-button v-if="currentStep === 2" type="primary" @click="handleComplete">{{ $t('返回个人资料') }}</el-button>
          <el-button v-else-if="currentStep === 1" type="primary" :loading="loading" @click="handleConfirm">{{
            $t('确认修改')
            }}</el-button>
          <el-button v-else type="primary" :loading="loading" @click="handleNextStep">{{ $t('下一步') }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import VerificationCodeInput from '@/views/account/profile/components/VerificationCodeInput.vue'
import useUserStore from '@/store/modules/user'
import { ApiSendEmail,memberverifyEmail } from '@/api/public'
import { ApiUpdateEmail } from '@/api/mine'
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const router = useRouter()
const userStore = useUserStore()
const currentEmail = userStore.userInfo?.member.email || '' // TODO: 从用户数据中获取

const currentStep = ref(0)
const loading = ref(false)
const verificationCode = ref('')
const verifyError = ref(false)
const countdown = ref(0)
const newEmailCountdown = ref(0)

const formRef = ref<FormInstance>()
const form = ref({
  newEmail: '',
  verifyCode: ''
})
const newEmailVerifyError = ref(false)

const rules: FormRules = {
  newEmail: [
    { required: true, message: t('请输入新的邮箱地址'), trigger: 'blur' },
    { type: 'email', message: t('请输入正确的邮箱格式'), trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: t('请输入验证码'), trigger: 'blur' },
    { len: 6, message: t('请输入6位验证码'), trigger: 'blur' }
  ]
}

const maskEmail = (email: string = '') => {
  const [name, domain] = email.split('@')
  const maskedName = name?.charAt(0) + '*'.repeat((name?.length || 1) - 1)
  return `${maskedName}@${domain}`
}

const startCountdown = async (type: 'current' | 'new') => {
  let email = type == 'current'?currentEmail:form.value.newEmail
  ApiSendEmail({ email: email }).then(res => {
    ElMessage.success(res.msg || t('验证码已发送'))
    const target = type === 'current' ? countdown : newEmailCountdown
    target.value = 60
    const timer = setInterval(() => {
      target.value--
      if (target.value <= 0) clearInterval(timer)
    }, 1000)
  }).catch(() => {
    ElMessage.error(t('发送失败'))
  })
}

const handleResend = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success(t('验证码已发送'))
    startCountdown('current')
  } catch (error) {
    ElMessage.error(t('发送失败，请重试'))
  }
}

const handleNewEmailResend = async () => {
  try {
    if (!formRef.value) return
    await formRef.value.validateField(['newEmail'])
    await startCountdown('new')
  } catch (error) {
  }
}

const handleVerifyComplete = async () => {
  // TODO: 验证当前邮箱验证码
}

const handleNewEmailVerifyComplete = async () => {
  // TODO: 验证新邮箱验证码
}

const handleNextStep = async () => {
  if (!verificationCode.value || verificationCode.value.length !== 6) {
    verifyError.value = true;
    return
  }

  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    memberverifyEmail({code:verificationCode.value}).then(res=>{
      console.log(res,'res');
      if(res.code == 200){
        currentStep.value++
      }
    
    })
    
  } catch (error) {
    verifyError.value = true
  } finally {
    loading.value = false
  }
}

const handleConfirm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    await ApiUpdateEmail({
      email: form.value.newEmail,
      code: form.value.verifyCode
    })
    currentStep.value++
  } catch (error) {
    console.error('验证失败:', error)
  } finally {
    loading.value = false
  }
}


const handleCancel = () => {
  router.push('/account/profile')
}

const handleComplete = () => {
  router.push('/account/profile')
}

onMounted(() => {
  // startCountdown('current')
})
</script>

<style lang="scss" scoped>
.modify-email-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-content {
  flex: 1;
  padding: 32px 24px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.page-nav {
  margin-bottom: 24px;

  .breadcrumb {
    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: #565656;
        font-weight: normal;
        font-size: 14px;

        &:hover {
          color: #c45500;
        }

        i {
          margin-right: 4px;
          font-size: 12px;
        }
      }
    }
  }
}

.main-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 32px;
}

.page-title {
  font-size: 24px;
  color: #111;
  font-weight: 500;
  margin-bottom: 32px;
}

.steps {
  margin: 20px 0 30px;

  @media (max-width: 768px) {
    .step-title {
      display: none;
    }
  }
}

.step-container {
  min-height: 280px;
  position: relative;
}

.step-content {
  width: 100%;
  max-width: 360px;
  margin: 0 auto;
  padding: 0 20px;
}

.step-desc {
  text-align: center;
  color: #666;
  margin-bottom: 24px;
}

.resend-wrapper {
  margin-top: 16px;
  text-align: center;
}

.complete {
  text-align: center;
  padding: 32px 0;

  .success-icon {
    font-size: 48px;
    color: #52c41a;
    margin-bottom: 16px;
  }

  h3 {
    font-size: 18px;
    color: #333;
    margin-bottom: 8px;
  }

  p {
    color: #666;
  }
}

:deep(.el-form-item__label) {
  color: #333;
  font-weight: 500;
  padding-bottom: 8px;
}

.bottom-actions {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 16px;

  .el-button {
    min-width: 120px;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
